<template>
  <div class="booking-page">
    <div class="booking-container">
      <h1 class="page-title">预约拍摄</h1>

      <el-steps :active="currentStep" finish-status="success" class="booking-steps">
        <el-step title="选择套餐及拍摄日期" />
        <el-step title="选择摄影师" />
        <el-step title="填写信息" />
        <el-step title="确认预约" />
      </el-steps>

      <!-- 套餐选择部分 -->
      <div v-if="currentStep === 0" class="section packages-section">
        <!-- <h2 class="section-title">选择套餐</h2> -->
        <el-row :gutter="20">
          <el-col :span="8" v-for="pkg in packages" :key="pkg.id">
            <el-card class="package-card" :body-style="{ padding: '0px' }">
              <!-- <div class="image-wrapper">
                <img :src="pkg.cover_image" class="package-image" />
              </div> -->
              <div class="package-info">
                <h3>{{ pkg.name }}</h3>
                <div class="price-info">
                  <div class="main-price">
                    <span class="current-price">¥{{ pkg.price }}</span>
                    <span class="original-price">¥{{ pkg.original_price }}</span>
                  </div>
                  <div class="deposit-info">
                    <span class="deposit">定金: ¥{{ pkg.deposit }}</span>
                  </div>
                </div>
                <!-- 主要特点展示 -->
                <div class="features">
                  <el-tag
                    v-for="(gift, index) in pkg.team_service.slice(0, 3)"
                    :key="index"
                    size="small"
                    class="feature-tag"
                  >
                    {{ gift }}
                  </el-tag>
                  <el-tag v-if="pkg.team_service.length > 3" size="small" type="info">
                    更多...
                  </el-tag>
                </div>
                <div class="actions">
                  <el-button type="primary" @click="handleViewDetail(pkg)"> 查看详情 </el-button>
                  <el-button
                    type="success"
                    @click="handleSelectPackage(pkg)"
                    :disabled="selectedPackage?.id === pkg.id"
                  >
                    {{ selectedPackage?.id === pkg.id ? '已选择' : '选择' }}
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
          <div class="date-selection">
            <div class="calendar-wrapper">
              <el-date-picker
                v-model="selectedDate"
                type="date"
                placeholder="选择拍摄起始日期"
                :disabled-date="isDateDisabled"
                value-format="YYYY-MM-DD"
              />
            </div>
            <div>
              <el-alert type="info" :closable="false" center show-icon>
                具体拍摄时间默认为起始日期后三天内
              </el-alert>
            </div>
          </div>
        </el-row>
      </div>

      <!-- 步骤3：选择摄影师 -->
      <div v-if="currentStep === 1" class="section photographers-section">
        <!-- <h2 class="section-title">选择摄影师</h2> -->
        <el-row :gutter="20">
          <div v-if="availablePhotographers.length == 0">暂无可用摄影师，请重新选择拍摄时间</div>
          <el-col :span="8" v-for="photographer in availablePhotographers" :key="photographer.id">
            <el-card class="photographer-card" :body-style="{ padding: '0px' }">
              <div class="image-wrapper">
                <img :src="photographer.avatar" class="photographer-avatar" />
              </div>
              <div class="photographer-info">
                <h3>{{ photographer.nickname }}</h3>
                <!-- <div class="level">
                  <el-rate
                    v-model="photographer.level"
                    :max="4"
                    disabled
                    show-score
                    text-color="#ff9900"
                  />
                </div> -->
                <div class="specialties">
                  <el-tag
                    v-for="specialty in photographer.specialties"
                    :key="specialty"
                    size="small"
                  >
                    {{ specialtiesMap[specialty] || specialty }}
                  </el-tag>
                </div>
                <p class="introduction">{{ photographer.introduction }}</p>
                <div class="actions">
                  <el-button
                    v-if="!photographer.isBooked"
                    type="success"
                    @click="handleSelectPhotographer(photographer)"
                    :disabled="selectedPhotographer?.id === photographer.id"
                  >
                    {{ selectedPhotographer?.id === photographer.id ? '已选择' : '选择' }}
                  </el-button>
                  <el-button v-if="photographer.isBooked" type="warning" disabled="true">
                    {{ '无档期' }}
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 步骤4：填写信息 -->
      <div v-if="currentStep === 2" class="step-content">
        <el-form
          ref="bookingFormRef"
          :model="bookingForm"
          :rules="bookingRules"
          label-width="100px"
          class="booking-form"
        >
          <el-form-item label="新人姓名" prop="name">
            <el-input v-model="bookingForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="bookingForm.phone" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="bookingForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="婚期" prop="weddingDate">
            <el-date-picker
              v-model="bookingForm.weddingDate"
              type="date"
              placeholder="请选择婚期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="bookingForm.remarks"
              type="textarea"
              rows="4"
              placeholder="请输入其他需求或备注"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤4：确认信息 -->
      <div v-if="currentStep === 3" class="step-content">
        <el-descriptions title="预约信息确认" :column="1" border>
          <el-descriptions-item label="套餐名称">
            {{ selectedPackage?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="套餐价格">
            ¥{{ selectedPackage?.price }}
          </el-descriptions-item>
          <el-descriptions-item label="摄影师">
            {{ selectedPhotographer?.nickname }}
          </el-descriptions-item>
          <el-descriptions-item label="开始拍摄日期">
            {{ selectedDate }}
          </el-descriptions-item>
          <!-- <el-descriptions-item label="拍摄时段">
            {{ selectedTime }}
          </el-descriptions-item> -->
          <el-descriptions-item label="新人姓名">
            {{ bookingForm.name }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ bookingForm.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="电子邮箱">
            {{ bookingForm.email }}
          </el-descriptions-item>
          <el-descriptions-item label="婚期">
            {{ formatDate(bookingForm.weddingDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ bookingForm.remarks || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 步骤控制按钮 -->
      <div class="step-actions">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button v-if="currentStep < 3" type="primary" @click="nextStep" :disabled="!canProceed">
          下一步
        </el-button>
        <el-button v-else type="success" :loading="submitting" @click="submitBooking">
          确认预约
        </el-button>
      </div>

      <!-- 套餐详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        :title="currentPackage?.name"
        width="50%"
        destroy-on-close
      >
        <div class="package-detail" v-if="currentPackage">
          <!-- 套餐图片轮播 -->
          <!-- <el-carousel height="auto" class="detail-carousel">
            <el-carousel-item
              class="carousel-image"
              v-for="photo in currentPackage.photos"
              :key="photo"
            >
              <img :src="photo" />
            </el-carousel-item>
          </el-carousel> -->

          <!-- 套餐价格信息 -->
          <div class="detail-price">
            <div class="price-main">
              <span class="current">¥{{ currentPackage.price }}</span>
              <span class="original">¥{{ currentPackage.original_price }}</span>
            </div>
            <div class="deposit">定金：¥{{ currentPackage.deposit }}</div>
          </div>

          <!-- 套餐描述 -->
          <div class="detail-description">
            {{ currentPackage.description }}
          </div>

          <el-alert type="info" :closable="false" center show-icon>
            若有增添服装、影像产品的需求，请在确认订单时新增
          </el-alert>

          <!-- 套餐特点 -->
          <div class="detail-section">
            <h4>套餐豪礼</h4>
            <div class="tags-container">
              <el-tag
                v-for="(item, index) in currentPackage.package_gift"
                :key="index"
                class="detail-tag"
              >
                {{ item }}
              </el-tag>
            </div>
          </div>

          <!-- 服务内容 -->
          <div class="detail-section">
            <h4>团队服务</h4>
            <ul class="service-list">
              <li v-for="(service, index) in currentPackage.team_service" :key="index">
                <el-icon><Check /></el-icon>
                {{ service }}
              </li>
            </ul>
          </div>

          <!-- 拍摄产品 -->
          <div class="detail-section">
            <h4>影像产品</h4>
            <ul class="product-list">
              <li v-for="(product, index) in currentPackage.image_product" :key="index">
                <el-icon><Picture /></el-icon>
                {{ product }}
              </li>
            </ul>
          </div>

          <!-- 注意事项 -->
          <div class="detail-section">
            <h4>温馨提示</h4>
            <ul class="tips-list">
              <li v-for="(tip, index) in currentPackage.tips" :key="index">
                <el-icon><WarningFilled /></el-icon>
                {{ tip }}
              </li>
            </ul>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
            <el-button
              type="primary"
              @click="handleSelectFromDetail"
              :disabled="selectedPackage?.id === currentPackage?.id"
            >
              {{ selectedPackage?.id === currentPackage?.id ? '已选择' : '选择此套餐' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import type { Package } from '@/types/package'
import { getPackages } from '@/api/package'
import type { Photographer } from '@/types/photographer'
import { getAvailablePhotographersList } from '@/api/photographer'
import { createBooking } from '@/api/booking'
import { useRouter } from 'vue-router'

const router = useRouter()
const currentStep = ref(0)
const submitting = ref(false)
const bookingFormRef = ref<FormInstance>()

const specialtiesMap: Record<string, string> = {
  wedding: '婚纱摄影',
  portrait: '写真',
  family: '全家照',
  children: '儿童摄影',
  maternity: '孕妇照',
}

// 套餐数据
const packages = ref<Package[]>([])
// const packages = ref([
// {
//   id: 1,
//   name: '基础套餐',
//   price: 4999,
//   image: '/images/package1.jpg',
//   features: ['8小时拍摄', '50张精修片', '提供化妆造型', '赠送精美相册'],
// },
// {
//   id: 2,
//   name: '高级套餐',
//   price: 6999,
//   image: '/images/package2.jpg',
//   features: ['12小时拍摄', '100张精修片', '提供化妆造型', '赠送精美相册', '赠送微电影'],
// },
// {
//   id: 3,
//   name: '豪华套餐',
//   price: 9999,
//   image: '/images/package3.jpg',
//   features: [
//     '2天拍摄',
//     '200张精修片',
//     '提供化妆造型',
//     '赠送精美相册',
//     '赠送微电影',
//     '赠送婚纱礼服',
//   ],
// },
// ])

const selectedPackage = ref<Package | null>(null)
const selectedDate = ref('')

const bookingForm = ref({
  name: '',
  phone: '',
  email: '',
  weddingDate: '',
  remarks: '',
})

const bookingRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  weddingDate: [{ required: true, message: '请选择婚期', trigger: 'change' }],
}

// 判断是否可以进行下一步
const canProceed = computed(() => {
  switch (currentStep.value) {
    case 0:
      return selectedPackage.value !== null && selectedDate.value
    case 1:
      return selectedPhotographer.value !== null
    case 2:
      return true // 表单验证在nextStep中处理
    default:
      return true
  }
})

const fetchPackages = async () => {
  try {
    const { data } = await getPackages()
    packages.value = data.result
  } catch (error) {
    ElMessage.error('获取套餐数据失败')
  } finally {
  }
}

// 日期和时间处理
const isDateDisabled = (date: Date) => {
  const currentDate = new Date()
  currentDate.setHours(0, 0, 0, 0) // 设置时间为当天的开始

  // 检查是否在今天之前
  return date <= currentDate
}

const formatDate = (date: Date | string | null) => {
  if (!date) return ''
  return dayjs(date).format('YYYY-MM-DD')
}

// 步骤控制
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const nextStep = async () => {
  if (currentStep.value === 0) {
    fetchPhotographers()
  }
  if (currentStep.value === 3) {
    if (!bookingFormRef.value) return
    const valid = await bookingFormRef.value.validate()
    if (!valid) return
  }

  if (currentStep.value < 4) {
    currentStep.value++
  }
}

// 提交预约
const submitBooking = async () => {
  submitting.value = true
  try {
    await createBooking({
      package_id: selectedPackage.value!.id,
      photographer_id: selectedPhotographer.value!.id,
      shooting_date: selectedDate.value,
      customer_name: bookingForm.value.name,
      customer_phone: bookingForm.value.phone,
      customer_email: bookingForm.value.email,
      wedding_date: bookingForm.value.weddingDate,
      remark: bookingForm.value.remarks,
    })

    ElMessage.success('预约成功')
    router.push('/booking-manage')
  } catch (error) {
    ElMessage.error('预约失败，请重试')
  } finally {
    submitting.value = false
  }
}

const currentPackage = ref<Package | null>(null)
const detailDialogVisible = ref(false)

// 查看套餐详情
const handleViewDetail = (pkg: Package) => {
  currentPackage.value = pkg
  detailDialogVisible.value = true
}

// 从详情对话框中选择套餐
const handleSelectFromDetail = () => {
  if (currentPackage.value) {
    handleSelectPackage(currentPackage.value)
    detailDialogVisible.value = false
  }
}

// 选择套餐
const handleSelectPackage = (pkg: Package) => {
  selectedPackage.value = pkg
  // 其他选择套餐后的逻辑...
  // fetchPhotographers()
}

const availablePhotographers = ref<Photographer[]>([])
const selectedPhotographer = ref<Photographer | null>(null)

// MARK: 获取摄影师列表
const fetchPhotographers = async () => {
  try {
    const { data } = await getAvailablePhotographersList({
      level: selectedPackage.value?.photographer_level,
      shootingDate: selectedDate.value,
    })
    availablePhotographers.value = data.data.items
  } catch (error) {
    ElMessage.error('获取摄影师列表失败')
  }
}

// 选择摄影师
const handleSelectPhotographer = (photographer: Photographer) => {
  selectedPhotographer.value = photographer
}

onMounted(() => {
  fetchPackages()
})
</script>

<style scoped>
.booking-page {
  padding: 120px 0 40px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.booking-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  background: white;
  border-radius: 20px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.page-title {
  text-align: center;
  margin-bottom: 2rem;
  color: var(--primary-color);
}

.booking-steps {
  margin-bottom: 3rem;
}

.step-content {
  margin: 2rem 0;
}

.packages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
}

.package-card {
  position: relative;
  margin-bottom: 20px;
}

/* 重置 el-card 默认样式 */
.package-card :deep(.el-card__body) {
  padding: 0;
}

/* 图片容器 */
.image-wrapper {
  position: relative;
  width: 100%;
  /* padding-bottom: 66.67%; 3:2 比例 */
}

/* 封面图片 */
.package-image {
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 内容区域 */
.package-info {
  padding: 16px;
}

/* 标题 */
.package-info h3 {
  margin: 0 0 12px;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

/* 价格信息 */
.price-info {
  margin-bottom: 12px;
}

.main-price {
  margin-bottom: 4px;
}

.current-price {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 8px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.deposit-info {
  font-size: 13px;
  color: #666;
}

/* 特点标签 */
.features {
  margin: 12px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 操作按钮 */
.actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: space-between;
}

/* 悬停效果 */
.package-card {
  transition: transform 0.3s ease;
}

.package-card:hover {
  transform: translateY(-5px);
}

.package-card.selected {
  border: 2px solid var(--el-color-primary);
}

.package-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: var(--el-color-danger);
  font-size: 1.5rem;
  font-weight: bold;
}

.package-features {
  list-style: none;
  padding: 0;
}

.package-features li {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.date-selection {
  margin-left: 10px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.calendar-wrapper {
  flex-shrink: 0;
}

.date-selection :deep(.el-alert) {
  margin: 0;
}

.calendar-cell {
  height: 100%;
  padding: 8px;
  text-align: center;
  cursor: pointer;
}

.calendar-cell.available {
  cursor: pointer;
  color: var(--el-color-primary);
}

.calendar-cell.unavailable {
  color: var(--el-text-color-disabled);
  cursor: not-allowed;
  background-color: var(--el-fill-color-light);
}

.calendar-cell:hover.available {
  background-color: var(--el-color-primary-light-9);
}

.time-slots {
  padding: 1rem;
  background: var(--el-bg-color-page);
  border-radius: 4px;
}

.time-radio-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
  margin-top: 1rem;
}

.booking-form {
  max-width: 600px;
  margin: 0 auto;
}

.step-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-top: 2rem;
  padding-top: 2rem;
  border-top: 1px solid var(--el-border-color);
}

@media (max-width: 768px) {
  .booking-container {
    padding: 1rem;
  }

  .packages-grid {
    grid-template-columns: 1fr;
  }
}

.features {
  margin: 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.feature-tag {
  margin-right: 5px;
}

.detail-price {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.price-main {
  margin-bottom: 10px;
}

.price-main .current {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.price-main .original {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.detail-description {
  margin: 20px 0;
  line-height: 1.6;
  color: #666;
}

.detail-section {
  margin: 20px 0;
}

.detail-section h4 {
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.detail-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.service-list,
.product-list,
.tips-list {
  list-style: none;
  padding: 0;
}

.service-list li,
.product-list li,
.tips-list li {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.service-list .el-icon {
  color: #67c23a;
}

.product-list .el-icon {
  color: #4073ff;
}

.tips-list .el-icon {
  color: #fab641;
}

.price-info {
  margin: 10px 0;
}

.main-price {
  margin-bottom: 5px;
}

.current-price {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.deposit {
  color: #e6a23c;
}

/* .actions {
  margin-top: auto;
  padding-top: 10px;
  display: flex;
  gap: 10px;
  justify-content: space-between;
} */

/* 套餐详情对话框样式 */
.detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.detail-content {
  padding: 20px;
}

.detail-carousel {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.carousel-image {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 500px; /* 按需设置容器高度 */
  overflow: hidden;
}

.carousel-image img {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

/* 摄影师卡片样式 */
.photographer-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.photographer-card:hover {
  transform: translateY(-5px);
}

.photographer-avatar {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

.photographer-info {
  padding: 15px;
}

.photographer-info h3 {
  margin: 0 0 10px;
  font-size: 18px;
  color: #333;
}

.level {
  margin-bottom: 10px;
}

.specialties {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.introduction {
  margin: 10px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.shooting-date-tip {
  margin-bottom: 20px;
}

.shooting-date-tip :deep(.el-alert) {
  background-color: var(--el-color-info-light-9);
  padding: 12px 20px;
}
</style>
